package com.elite.ngs.websocket;

import com.elite.ngs.beans.Staff;
import com.wisdge.web.springframework.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Map;

@Component
public class NgsHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
    private static final Logger log = LoggerFactory.getLogger(NgsHandshakeInterceptor.class);

    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.debug("Before WebSocketHandler: {}", wsHandler.getClass().getName());

        URI getURI = request.getURI();
        log.debug("Before WebSocket Target URI: {}", getURI);

        if (getURI.getHost().contains("127.0.0.1")) {
            return true;
        }

        HttpServletRequest servletRequest = ((ServletServerHttpRequest)request).getServletRequest();
        Staff staff = (Staff)WebUtils.getSessionAttribute(servletRequest, "staff");
        if (staff != null)
            return super.beforeHandshake(request, response, wsHandler, attributes);
        return false;
    }

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        log.debug("Last WebSocketHandler: {}", ((ExceptionWebSocketHandlerDecorator)wsHandler).getLastHandler().getClass().getName());
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
